package dnl.util.ui.table;


import java.util.Comparator;


/**
 * 
 * 
 * @author <a href="mailto:daniel@nlayers.com">Daniel Or</a>
 */
public final class RowComparator implements Comparator<RowData> {
	//~ Instance fields
	// ------------------------------------------------------------------------------
	int column;
	boolean ascending;
	private int returnVal = 1;
	@SuppressWarnings("unchecked")
	private Comparator typedComparator;

	//~ Constructors
	// ---------------------------------------------------------------------------------
	/**
	 * Creates a new <code>RowComparator</code>.
	 *  
	 */
	public RowComparator(int column, boolean ascending, Comparator<?> typedComparator) {
		this.column = column;
		this.setAscending(ascending);
		this.typedComparator = typedComparator;
	}

	//~ Methods
	// --------------------------------------------------------------------------------------

	/**
	 * 
	 * @param r1
	 * @param r2
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public int compare(RowData r1, RowData r2) {
		// the types may be int, long or even strings
		Object l1 = r1.getObjectAt(column);
		Object l2 = r2.getObjectAt(column);
		return typedComparator.compare(l1, l2) * returnVal;
	}

	//	/**
	//	 * 
	//	 * @param rowData1
	//	 * @param rowData2
	//	 * @return
	//	 */
	//	public int compare(Object rowData1, Object rowData2) {
	//		if(rowData1 instanceof RowData && rowData1 instanceof RowData){
	//			return compare((RowData)rowData1, (RowData)rowData2);
	//		}
	//		Object o1 = rowData1 == null ? null : ((Object[])rowData1)[column];
	//		Object o2 = rowData1 == null ? null : ((Object[])rowData2)[column];
	//		return typedComparator.compare(o1, o2) * returnVal;
	//	}


	/**
	 * @return Returns the typedComparator.
	 */
	public Comparator<?> getTypedComparator() {
		return typedComparator;
	}
	/**
	 * @param typedComparator The typedComparator to set.
	 */
	@SuppressWarnings("unchecked")
	public void setTypedComparator(Comparator typedComparator) {
		this.typedComparator = typedComparator;
	}		
	
	/**
	 * @param i
	 */
	public void setColumn(int i) {
		column = i;
	}

	/**
	 * @return
	 */
	public int getColumn() {
		return column;
	}

	/**
	 * @param b
	 */
	public void setAscending(boolean b) {
		ascending = b;
		if (b)
			returnVal = -1;
		else
			returnVal = 1;
	}

	/**
	 * @return
	 */
	public boolean isAscending() {
		return ascending;
	}

	
}
